package matlab;

public class Binary {
	
	public static long longFrom(byte[] data, int offset)
	{
		long x = 0;
		for (int i = 7; i >= 0; i--) {
			long y = data[offset+i]&0xFF;
			x = (x<<8) | y;
		}
		return x;
	}

	public static long longFromLE(byte[] data, int offset)
	{
		return  ((data[offset+7]&0xFF)<<0) |
				((data[offset+6]&0xFF)<<8) |
				((data[offset+5]&0xFF)<<16) |
				((data[offset+4]&0xFF)<<24) |
				((data[offset+3]&0xFF)<<32) |
				((data[offset+2]&0xFF)<<40) |
				((data[offset+1]&0xFF)<<48) |
				((data[offset+0]&0xFF)<<56);		
	}

	public static int intFrom(byte[] data, int offset)
	{
		return  ((data[offset+0]&0xFF)<<0) |
				((data[offset+1]&0xFF)<<8) |
				((data[offset+2]&0xFF)<<16) |
				((data[offset+3]&0xFF)<<24);		
	}
	
	public static byte[] intBytes(int v)
	{
		byte[] data = new byte[4];
		data[0] = (byte) ((v>>0)&0xFF);
		data[1] = (byte) ((v>>8)&0xFF);
		data[2] = (byte) ((v>>16)&0xFF);
		data[3] = (byte) ((v>>24)&0xFF);
		return data;
	}

	public static short shortFrom(byte[] data, int offset)
	{
		return  (short) 
				(((data[offset+0]&0xFF)<<0) |
				 ((data[offset+1]&0xFF)<<8));		
	}

	public static void shortTo(byte[] data, int offset, short value)
	{
		data[offset+0] = (byte) (value&0xFF);
		data[offset+1] = (byte) ((value>>8)&0xFF);
	}

	public static double doubleFrom(byte[] data, int offset) 
	{
		long bits = longFrom(data, offset);
		return Double.longBitsToDouble(bits);
	}
	
	public static String stringFrom16bit(byte[] data) {
		StringBuffer sb = new StringBuffer();
		int n = data.length/2;
		for (int i = 0; i < n; i++) {
			byte b = data[i*2];
			sb.append((char)b);
		}
		return sb.toString();
	}
}
